window.GoogleDirections = function(ymap,resultDiv){
		this.ymap = ymap;
		this.resultDiv = resultDiv;
		this.directionsService = new google.maps.DirectionsService();
		this.directionDisplay = new google.maps.DirectionsRenderer({preserveViewport:true});
		this.googleMap = ymap.map;
		this.directionDisplay.setMap(ymap.map);
		this.appendToContextMenu();
		this.currentStart=null;
		this.currentEnd=null;
	}
	window.GoogleDirections.prototype = {
		callRoute : function(start,end){
			var me= this;
			var request = {
			    origin:start, 
			    destination:end,
			    travelMode: google.maps.DirectionsTravelMode.DRIVING
			  };
			this.directionsService.route(request, function(result, status) {
			    if (status == google.maps.DirectionsStatus.OK) {
			      me.directionDisplay.setDirections(result);
			      if(me.resultDiv){
			      	me.listResult(result);
			      }
			    }
			    else{
			    	alert("对不起，路线请求失败，请稍后再试");
			    }
			  });
		},
		
		appendToContextMenu : function(){
			var me = this;
			var menu = this.ymap.mapContextMenu;
			if(menu){
				menu.addItem("设为起点",function(){
					
					me.currentStart = menu.popupLocation;
					if(me.currentEnd){
						me.callRoute(me.currentStart,me.currentEnd);
					}
				},"image/circle_greenA.png");
				menu.addItem("设为终点",function(ymap){
					me.currentEnd = menu.popupLocation;
					if(me.currentStart){
						me.callRoute(me.currentStart,me.currentEnd);
					}
				},"image/circle_greenB.png");
			}
		},
		
		listResult:function(result){
			var me = this;
			var parent = $("#"+this.resultDiv);
			parent.empty();
			var root = $("<div></div>").appendTo(parent);
			root.attr("id","googleDirectionsResult");
			
			var leg = result.routes[0].legs[0];
			var startPointDiv = $("<div id='startPoint'></div>").appendTo(root).html("<img src='image/circle_greenA.png'>"+removedress(leg.start_address));
			startPointDiv.click(function(){
				var gmap = me.ymap.map;
				gmap.panTo(leg.start_location);
			});
			startPointDiv.addClass("resultItem");
			
			
			var endPointDiv = $("<div id='endPoint'></div>").appendTo(root).html("<img src='image/circle_greenB.png'>"+removedress(leg.end_address));
			endPointDiv.click(function(){
				var gmap = me.ymap.map;
				gmap.panTo(leg.end_location);
			});
			endPointDiv.addClass("resultItem");
			var lucheng = $("<div id='rodeline'> 路线：</div>").appendTo(root);
			var steps = leg.steps;
			for (var i = 0; i < steps.length; i++) {
				var step = steps[i];
				addStepDiv(i+1,step);
			}
			 function addStepDiv(i,step){
			 	
			 	var stepDiv = $("<div></div>").html(i+"."+step.instructions).appendTo(lucheng);
				stepDiv.click(function(){
					var gmap = me.ymap.map;
					gmap.panTo(step.start_location);
				});
				stepDiv.addClass("resultItem");
			 }
			 
			 function removedress(dress){
               return dress.split("邮政编码")[0];
			 }
		}
	}
